package kt;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import kt.dal.DAL;
import kt.dal.DBPoolX;
import kt.dal.DBPoolXName;
import kt.smpp.pdu.SMSResponse;
import kt.util.SmsUtil;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import vn.vnpay.www.VASContent.MTSendSoapStub;

import com.mysql.jdbc.Util;

/**
 * Example class to submit a message to a SMSC using synchronous communication.
 * This class simply binds to the server, submits a message, and then unbinds.
 * 
 * @see ie.omk.smpp.examples.ParseArgs ParseArgs for details on running this
 *      class.
 */
public class SendTempMTJob implements Job {
	//private Log logger = LogFactory.getLog(SendMTJob.class);
    private static final Logger logger = LogManager.getLogger(SendTempMTJob.class);
   
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		java.sql.Connection conn = null;
		String strSQL = "select ID, RECEIVER_NUMBER, INFO, SERVICE_NUMBER from TMP_SMS_SEND_QUEUE where "
			+"time_send > DATE_ADD(now(),INTERVAL -5 MINUTE) and time_send < now() order by ID";
		try {
			// logger.info("get MT of " + operator);
			conn = DriverManager.getConnection(
					"jdbc:mysql://localhost/www_school?autoReconnect=true",
					"root", "admin123ewq");
			PreparedStatement preStmt = conn.prepareStatement(strSQL);
			ResultSet rs = preStmt.executeQuery();
			
			while (rs.next()) {	
				SMSResponse response = new SMSResponse();
				response.setId(rs.getInt("ID"));
				String receive_number = rs.getString("RECEIVER_NUMBER");
				
				// check is Metfone Number
				if(SmsUtil.isMetfoneNumber(receive_number)){
					response.setSenderNumber(rs.getString("RECEIVER_NUMBER"));
					response.setReceiverNumber(rs.getString("RECEIVER_NUMBER"));				
					//TODO need to change here
					response.setServiceNumber("1765");
					response.setMobileOperator("Metfone");
					response.setContentType(0);
					response.setInfo(rs.getString("INFO"));
					response.setRequestId(0);
					response.setUnicode(false);
					sendTempMT(response);		
				}
				// is other
				else {
					try {
						String destination = receive_number;
						String sendFrom = "2122";
						if(SmsUtil.isCellCardNumber(receive_number)){
							sendFrom = "1522";
							logger.info( "Number is CellCard");
						}
						String keywordName = "ANTTEL";
						String outContent = rs.getString("INFO");
						String chargingFlag= "0";
						String MOSeqNo = "0";
						String totalMessage="1"; 
						String contentType = "0";
						String secretCode = "Antel1522GLCHAL";
						logger.info("Secret Code: " + secretCode);
						// 
						MTSendSoapStub mtsend = new MTSendSoapStub();
						mtsend.sendMT(destination, sendFrom, keywordName, outContent, chargingFlag, MOSeqNo, totalMessage, contentType, secretCode);
					} catch (Exception e) {
						// TODO: handle exception
						logger.warn("Combopay Exception  :"+ e.getMessage());
					}
					
					
				}
				logger.info("delete tempMT id = " + response.getId());
				preStmt = conn.prepareStatement("Delete from TMP_SMS_SEND_QUEUE where ID = ?");
				preStmt.setInt(1, response.getId());
				preStmt.executeUpdate();
				preStmt.close();
			}
			rs.close();
			preStmt.close();
			
		} catch (Exception e) {
			logger.error("Error executing SQL " + strSQL, e);
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					logger.error("error when close the conn", e);
				}
			}
		}
	}

	private void sendTempMT(SMSResponse res) {
		PreparedStatement preStmt = null;
		Connection sqlCnn = null;
		DBPoolX smsPool = null;
		logger.info("send tempMT " + res);
		try {
			smsPool = DBPoolX.getInstance(DBPoolXName.SMS_DEFAULT);
			sqlCnn = smsPool.getConnection();
			if(res != null){
	
				String strSQL = "INSERT INTO SMS_SEND_QUEUE ( SENDER_NUMBER, RECEIVER_NUMBER, SERVICE_NUMBER, MOBILE_OPERATOR, COMMAND_CODE, "
	 + " CONTENT_TYPE, MESSAGE_TYPE, INFO, GEN_DATE) "
	 + " VALUES (?, ? , ?, ?, 'INV', 0, 0, ? , now())";
	
				preStmt = sqlCnn.prepareStatement(strSQL);
				preStmt.setString(1, res.getSenderNumber());
				preStmt.setString(2, res.getReceiverNumber());
				preStmt.setString(3, res.getServiceNumber());
				preStmt.setString(4, res.getMobileOperator());
				preStmt.setString(5, res.getInfo());
				preStmt.executeUpdate();
				preStmt.close();
			}	
		}
		catch (Exception e){
			logger.error("can not insert MT to SMS_Send_Queue", e);
		} finally {
			if(smsPool != null){
				smsPool.releaseConnection(sqlCnn, preStmt);
			}
		}
	}
}

